package com.noah.note.ui;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.noah.note.R;
import com.noah.note.global.BaseActivity;
import com.noah.note.global.Const;
import com.noah.note.manager.HttpManager;
import com.noah.note.presenter.LoginPresenter;
import com.noah.note.utils.EncryptUtils;
import com.noah.note.utils.FileUtils;
import com.noah.note.utils.ImageUtils;
import com.noah.note.utils.LogUtils;
import com.noah.note.utils.SPUtils;
import com.noah.note.utils.ToastUtils;
import com.noah.note.view.LoginView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import top.zibin.luban.OnCompressListener;


/**
 * 登录
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginView {
    public static final int LOGIN_STATE = 0;//显示登录页面
    public static final int REGISTER_STATE = 1;//显示注册页面

    @BindView(R.id.tilNickName)
    TextInputLayout tilNickName;
    @BindView(R.id.etNickName)
    EditText etNickName;
    @BindView(R.id.etUsername)
    EditText etUsername;
    @BindView(R.id.etPassword)
    EditText etPassword;
    @BindView(R.id.tvRegister)
    TextView tvRegister;
    @BindView(R.id.tvForgetPassword)
    TextView tvForgetPassword;
    @BindView(R.id.tvWelcomeTitle)
    TextView tvWelcomeTitle;
    @BindView(R.id.btnLogin)
    Button btnLogin;

    private int currentState = LOGIN_STATE;

    @Override
    protected LoginPresenter initPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        String username = (String) SPUtils.get(Const.SP_USERNAME, "");
        etUsername.setText(username);
    }

    private void goLogin() {
        etUsername.setError(null);
        etPassword.setError(null);
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(username) || username.length() < 6) {
            etUsername.setError(getString(R.string.error_username));
            etUsername.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            etPassword.setError(getString(R.string.error_password));
            etPassword.requestFocus();
            return;
        }
        mPresenter.login(username, EncryptUtils.MD5(password));
    }

    private void goRegister() {
        etNickName.setError(null);
        etUsername.setError(null);
        etPassword.setError(null);
        String nickname = etNickName.getText().toString();
        String username = etUsername.getText().toString();
        String password = EncryptUtils.MD5(etPassword.getText().toString());

        if (TextUtils.isEmpty(nickname)) {
            etNickName.setError(getString(R.string.error_nickname));
            etNickName.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(username) || username.length() < 6) {
            etUsername.setError(getString(R.string.error_username));
            etUsername.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            etPassword.setError(getString(R.string.error_password));
            etPassword.requestFocus();
            return;
        }
        mPresenter.register(username, password, nickname);
    }

    private void showRegisterView() {
        tilNickName.setVisibility(View.VISIBLE);
        btnLogin.setText(R.string.register);
        tvRegister.setText(R.string.login_account);
//        tvForgetPassword.setVisibility(View.GONE);
        tvWelcomeTitle.setText(R.string.register_to_note);
        currentState = REGISTER_STATE;
    }

    private void showLoginView() {
        tilNickName.setVisibility(View.GONE);
        btnLogin.setText(R.string.login);
        tvRegister.setText(R.string.register_account);
//        tvForgetPassword.setVisibility(View.VISIBLE);
        tvWelcomeTitle.setText(R.string.welcome_to_note);
        currentState = LOGIN_STATE;
    }

    @OnClick({R.id.btnLogin, R.id.tvForgetPassword, R.id.tvRegister})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                switch (currentState) {
                    case LOGIN_STATE:
                        goLogin();
                        break;
                    case REGISTER_STATE:
                        goRegister();
                        break;
                }
                break;
            case R.id.tvForgetPassword:
                goActivity(RegisterActivity.class);
                break;
            case R.id.tvRegister:
                switch (currentState) {
                    case LOGIN_STATE:
                        showRegisterView();
                        break;
                    case REGISTER_STATE:
                        showLoginView();
                        break;
                }
//                showDialog();
                break;
        }
    }

    @Override
    public void loginSuccess() {
        SPUtils.save(Const.SP_USERNAME, etUsername.getText().toString().trim());
        goActivity(HomeActivity.class);
        finish();
    }

    @Override
    public void registerSuccess() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                showLoginView();
            }
        });
    }

    @Override
    public void loginFail() {

    }

    private void photoPicker() {//选择图片
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                photoPicker();
            } else {
                ToastUtils.show("请在设置中打开相机权限");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.i("resultCode = " + resultCode + ",requestCode = " + requestCode);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            //选取图片
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                compUpload(photos.get(0));//压缩上传图片,成功后发出图片地址的消息
            }
        }
    }

    //压缩图片,上传图片,发送图片地址
    public void compUpload(String path) {//压缩图片
        ImageUtils.showResult(new File(path));//查看压缩前的大小
        ImageUtils.compress(path, new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(final File file) {
                moveFile(file, 0);
                ImageUtils.showResult(file);//查看压缩后的大小
            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    //转到正常的文件夹中,修改名称,准备上传
    public void moveFile(final File file, final long recTime) {
        String md5 = EncryptUtils.MD5X("" + System.currentTimeMillis());
        String fileName = file.getAbsolutePath();
        LogUtils.i("movefile = " + fileName);
        String saveFilePath = "";
        if (fileName.contains(".jpg") || fileName.contains(".jpeg")) {
            saveFilePath = FileUtils.getAppFile(ImageUtils.IMG_PATH) + "/" + md5 + ".jpg";
        } else if (fileName.contains(".png")) {
            saveFilePath = FileUtils.getAppFile(ImageUtils.IMG_PATH) + "/" + md5 + ".png";
        } else if (fileName.contains(".gif")) {
            saveFilePath = FileUtils.getAppFile(ImageUtils.IMG_PATH) + "/" + md5 + ".gif";
        } else if (fileName.contains(".amr")) {
            saveFilePath = FileUtils.getAppFile(ImageUtils.RECORD_PATH) + "/" + md5 + ".amr";
        } else if (fileName.contains(".mp4")) {
            saveFilePath = FileUtils.getAppFile(ImageUtils.RECORD_PATH) + "/" + md5 + ".mp4";
        }
        if (TextUtils.isEmpty(saveFilePath)) {
            return;
        }
        File saveFile = FileUtils.makeFile(saveFilePath);
        if (FileUtils.copyFile(file, saveFile)) {//移动文件
            LogUtils.i("file=" + file.getAbsolutePath() + "  saveFile=" + saveFile.getAbsolutePath());
            String url = Const.BASE_HOST + Const.API_UPLOAD;
            HttpManager.getInstance().upload(url, saveFile.getAbsolutePath(), new HttpManager.OnUploadListener() {
                @Override
                public void onUploadSuccess(String result) {
                    LogUtils.i("onUploadSuccess = " + result);
                }

                @Override
                public void onUploading(int progress) {
                    LogUtils.i("progress = " + progress);
                }

                @Override
                public void onUploadFailed() {
                    LogUtils.i("onUploadFailed");
                }
            });

        }
    }
}

